package com.xyxeshang.es.music.backend.util;


import com.xyxeshang.es.music.backend.entity.User;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.Date;

/**
 * @author xyx-Eshang
 */
@Component
public class JwtUtil {
	/**
	 * 一级密钥
	 */
	@Value("${SECRET_KEY}")
	private static String secretKey;
	/**
	 * 过期的分钟
	 */
	private static Integer expireMinutes;
	/**
	 * 二级密钥：经过md5加密
	 */
	private static String SigningKey;

	/**
	 * 创建token
	 *
	 * @param user
	 * @return
	 */
	public static String createToken(User user) {
		Date expireDate = new Date(System.currentTimeMillis() + 1000 * 60 * expireMinutes);
		return Jwts.builder()
				//header
				.setHeaderParam("typ", "JWT")
				.setHeaderParam("alg", "HS256")
				//payload
				.claim("userOpenId", user.getUserOpenId())
				.setExpiration(expireDate)
				//signature
				.signWith(SignatureAlgorithm.HS256, SigningKey)
				//拼接起来
				.compact();
	}

	/**
	 * 解析token
	 *
	 * @param token
	 * @return
	 */
	public static Claims parseToken(String token) {
		JwtParser jwtParser = Jwts.parser();
		return jwtParser
				.setSigningKey(SigningKey)
				.parseClaimsJws(token)
				.getBody();
	}

	public static String getSigningKey() {
		return SigningKey;
	}

	public static void setSecretKey(String secretKey) {
		JwtUtil.secretKey = secretKey;
	}

	@Value("${JWT_SECRET_KEY}")
	private void setSigningKey(String secretKey) {
		JwtUtil.SigningKey = DigestUtils.md5DigestAsHex(secretKey.getBytes());
	}

	public static String getSecretKey() {
		return secretKey;
	}

	public static Integer getExpireMinutes() {
		return expireMinutes;
	}

	@Value("${JWT_EXPIRE_MINUTES}")
	public void setExpireMinutes(Integer expireMinutes) {
		JwtUtil.expireMinutes = expireMinutes;
	}
}
